<template>
  <div class="content">

    <div class="text main-text">欢迎使用 {{ this.$project.projectName }}</div>

    <div class="home-container">
      <el-row :gutter="20">
        <el-col :span="8" v-if="isAdmin">
          <div class="chart-container">
            <div class="chart-title">车辆状态统计</div>
            <div id="vehicleStatusChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-col>
        <el-col :span="isAdmin ? 8 : 12">
          <div class="chart-container">
            <div class="chart-title">物流状态统计</div>
            <div id="logisticsStatusChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-col>
        <el-col :span="isAdmin ? 8 : 12">
          <div class="chart-container">
            <div class="chart-title">运单状态统计</div>
            <div id="yundanStatusChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>
<script>
import router from '@/router/router-static'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      vehicleStatusData: [],
      vehicleStatusChart: null,
      logisticsChart: null,
      yundanChart: null,
      isAdmin: false
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.$storage.get('Token')) {
        this.$http({
          url: `${this.$storage.get('sessionTable')}/session`,
          method: "get"
        }).then(({ data }) => {
          if (data && data.code === 0) {
            // 判断是否为管理员
            this.isAdmin = data.data.role === '管理员';
            // 初始化图表
            this.$nextTick(() => {
              if (this.isAdmin) {
                this.getVehicleStatusData();
              }
              this.getLogisticsData();
              this.getYundanData();
            });
          } else {
            router.push({ name: 'login' })
          }
        });
      } else {
        router.push({ name: 'login' })
      }
    },
    getVehicleStatusData() {
      // 获取车辆状态数据
      this.$http({
        url: "dictionary/page?dicCode=cheliang_status_types&page=1&limit=100",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const statusTypes = data.data.list;
          console.log('车辆状态类型列表:', statusTypes);

          // 获取车辆数据
          this.$http({
            url: "cheliang/page?page=1&limit=1000",
            method: "get"
          }).then(({ data }) => {
            if (data && data.code === 0) {
              const vehicles = data.data.list;
              console.log('车辆列表数据:', vehicles);

              // 创建状态映射对象，用于快速查找状态名称
              const statusMap = {};
              statusTypes.forEach(status => {
                statusMap[status.codeIndex] = status.indexName;
              });

              // 初始化状态计数，确保所有状态类型都有计数
              const statusCount = {};
              statusTypes.forEach(status => {
                statusCount[status.indexName] = 0;
              });

              // 统计各状态的车辆数量
              vehicles.forEach(vehicle => {
                const statusCode = vehicle.cheliangStatusTypes;
                const statusName = statusMap[statusCode];
                console.log(`车辆ID: ${vehicle.id}, 状态码: ${statusCode}, 状态名称: ${statusName}`);
                
                if (statusName) {
                  statusCount[statusName]++;
                }
              });

              console.log('车辆状态统计结果:', statusCount);

              // 转换为图表数据格式，保持状态类型的顺序
              this.vehicleStatusData = statusTypes.map(status => ({
                name: status.indexName,
                value: statusCount[status.indexName] || 0
              }));
              console.log('图表数据:', this.vehicleStatusData);

              // 销毁旧图表实例
              if (this.vehicleStatusChart) {
                this.vehicleStatusChart.dispose();
              }
              
              // 重新初始化图表
              this.initChart();
            } else {
              console.error('获取车辆数据失败:', data.msg);
            }
          }).catch(error => {
            console.error('获取车辆数据出错:', error);
          });
        } else {
          console.error('获取状态类型失败:', data.msg);
        }
      }).catch(error => {
        console.error('获取状态类型出错:', error);
      });
    },
    initChart() {
      // 初始化图表
      this.vehicleStatusChart = echarts.init(document.getElementById('vehicleStatusChart'));

      // 设置图表选项
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: this.vehicleStatusData.map(item => item.name)
        },
        series: [
          {
            name: '车辆状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.vehicleStatusData
          }
        ]
      };

      // 使用配置项设置图表
      this.vehicleStatusChart.setOption(option);

      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        this.vehicleStatusChart.resize();
      });
    },
    getLogisticsData() {
      // 获取物流数据
      this.$http({
        url: 'wuliu/page',
        method: 'get',
        params: {
          page: 1,
          limit: 1000
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const logisticsList = data.data.list;
          console.log('物流列表:', logisticsList);

          // 统计各物流状态的数量
          const statusCount = {};

          logisticsList.forEach(item => {
            if (item.wuliuTypes && item.wuliuValue) {
              if (!statusCount[item.wuliuValue]) {
                statusCount[item.wuliuValue] = 0;
              }
              statusCount[item.wuliuValue]++;
            }
          });
          console.log('物流状态统计:', statusCount);

          // 准备图表数据
          const xAxisData = Object.keys(statusCount);
          const seriesData = Object.values(statusCount);
          const maxValue = Math.max(...seriesData);
          const interval = maxValue <= 10 ? 1 :
            maxValue <= 20 ? 2 :
              maxValue <= 30 ? 3 :
                maxValue <= 40 ? 4 : 5;

          // 初始化物流状态图表
          this.logisticsChart = echarts.init(document.getElementById('logisticsStatusChart'));

          // 设置图表选项
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'none'
              },
              formatter: '{b}: {c} 单'
            },
            xAxis: {
              type: 'category',
              data: xAxisData,
              axisLabel: {
                interval: 0,
                rotate: 0,
                formatter: function (value) {
                  // 每4个字换行
                  const regex = /.{1,4}/g;
                  return value.match(regex).join('\n');
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#999'
                }
              },
              splitLine: {
                show: false
              }
            },
            yAxis: {
              type: 'value',
              name: '数量（单）',
              min: 0,
              max: Math.ceil(maxValue / interval) * interval,
              interval: interval,
              axisLine: {
                lineStyle: {
                  color: '#999'
                }
              },
              splitLine: {
                show: false
              }
            },
            series: [{
              name: '物流数量',
              type: 'bar',
              data: seriesData,
              barWidth: '60%',
              itemStyle: {
                color: function (params) {
                  // 根据状态设置不同颜色
                  const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#FF8C00'];
                  return colorList[params.dataIndex % colorList.length];
                },
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowOffsetY: 5,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c} 单'
              }
            }]
          };

          // 使用配置项设置图表
          this.logisticsChart.setOption(option);

          // 监听窗口大小变化，调整图表大小
          window.addEventListener('resize', () => {
            this.logisticsChart.resize();
          });
        }
      })
    },
    getYundanData() {
      // 获取运单数据
      this.$http({
        url: 'yundan/page',
        method: 'get',
        params: {
          page: 1,
          limit: 1000
        }
      }).then(({ data }) => {
        console.log('运单完整响应数据:', data);  // 打印完整响应数据
        if (data && data.code === 0) {
          console.log('运单列表:', data.data.list);  // 打印运单列表
          // 打印每个运单的状态
          data.data.list.forEach((item, index) => {
            console.log(`运单 ${index + 1}:`, {
              id: item.id,
              statusType: item.yundanStatusTypes,
              statusValue: item.yundanStatusValue
            });
          });
          // 统计运单状态的数量
          const statusCount = {};

          data.data.list.forEach(item => {
            if (item.yundanStatusTypes && item.yundanStatusValue) {
              if (!statusCount[item.yundanStatusValue]) {
                statusCount[item.yundanStatusValue] = 0;
              }
              statusCount[item.yundanStatusValue]++;
            }
          });

          console.log('状态统计:', statusCount);  // 打印最终统计结果

          // 准备图表数据
          const xAxisData = Object.keys(statusCount)
          const seriesData = Object.values(statusCount)
          const maxValue = Math.max(...seriesData)
          const interval = maxValue <= 10 ? 1 :
            maxValue <= 20 ? 2 :
              maxValue <= 30 ? 3 :
                maxValue <= 40 ? 4 : 5

          // 初始化运单状态图表
          this.yundanChart = echarts.init(document.getElementById('yundanStatusChart'));

          // 设置图表选项
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'none'
              },
              formatter: '{b}: {c} 单'
            },
            grid: {
              backgroundColor: 'transparent'
            },
            xAxis: {
              type: 'category',
              data: xAxisData,
              axisLabel: {
                interval: 0,
                rotate: 0,
                formatter: function (value) {
                  // 每4个字换行
                  const regex = /.{1,4}/g;
                  return value.match(regex).join('\n');
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#999'
                }
              },
              splitLine: {
                show: false
              }
            },
            yAxis: {
              type: 'value',
              name: '数量（单）',
              min: 0,
              max: Math.ceil(maxValue / interval) * interval,
              interval: interval,
              axisLine: {
                lineStyle: {
                  color: '#999'
                }
              },
              splitLine: {
                show: false
              }
            },
            series: [{
              name: '运单数量',
              type: 'bar',
              data: seriesData,
              barWidth: '60%',
              itemStyle: {
                color: function (params) {
                  // 根据状态名称设置特定颜色
                  const statusName = xAxisData[params.dataIndex];
                  if (statusName === '已揽收') {
                    return '#8E44AD';  // 深紫色
                  }
                  const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#FF8C00', '#909399'];
                  return colorList[params.dataIndex % colorList.length];
                },
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowOffsetY: 5,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c} 单'
              }
            }]
          };

          // 使用配置项设置图表
          this.yundanChart.setOption(option);

          // 监听窗口大小变化，调整图表大小
          window.addEventListener('resize', () => {
            this.yundanChart.resize();
          });
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  min-height: 500px;
  text-align: center;

  .main-text {
    font-size: 38px;
    font-weight: bold;
    margin-top: 2%;
  }

  .text {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }

  .home-container {
    width: 100%;
    padding: 20px;
    margin-top: 20px;
  }

  .chart-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    height: 450px;

    .chart-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
      text-align: center;
    }
  }
}
</style>